<template>
   <PageWrapper contentFullHeight fixedHeight contentClass="flex" class="excel-form-model">
    <BasicFormForBOE class="common-search" @register="register">
        <template #advanceBefore>
          <Button
            type="default"
            class="mr-2"
            @click="handleExport">
            导出
          </Button>
        </template>
      </BasicFormForBOE>
    <div class="content-box">
        <ExcelTable v-for="(tableConfig, index) in tableConfigs" :key="index"
        :tableConfig="tableConfig" :pagination="pagination" v-bind="$attrs">
        
      </ExcelTable>
      </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, type Ref, onMounted, defineProps, nextTick } from 'vue'
import { Button } from 'ant-design-vue'
import { PageWrapper } from '@/components/Page'
import { BasicColumn } from '@/components/Table'
import { BasicFormForBOE, useForm, } from '@/components/Form';
import ExcelTable from './ExcelTable.vue'
import { getElExcelData, exportElExcelData } from '@/api/power/electricity/electricity'
import { getSearchFormSchema1 } from './data'
import { getDictListByCode } from '@/api/sys/dict'
  import {
    downloadByData,
  } from '@/utils/file/download';
  import { cloneDeep } from 'lodash-es';
import { isArray } from '@/utils/is';
import dayjs from 'dayjs';
const props = defineProps({
  groudIdDict: {
    type: String,
    default: 'electricity_statement'
  },
  dataClassify: {
    type: String
  },
  api: {
    type: Function
  },
  exportApi: {
    type: Function
  },
  pagination: {
    type: [Boolean, Object]
  },
  fiexdIndex: {
    type: [Number, String, Array],
    default: 3
  }
})
interface TableConfig {
  tableData: any[],
  title: string,
  columns: BasicColumn[]
}
const groupId = ref('')
const tableConfigs: Ref<any[]> = ref([])
const loading = ref(false)
const current = ref(1)
const [register, { getFieldsValue, setFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: getSearchFormSchema1({}),
  autoSubmitOnEnter: true,
  showResetButton: false,
  submitFunc: handleSearch
})
async function handleSearch() {
  tableConfigs.value = []
  loading.value = true
  const params = await getFieldsValue()
  try{
    let res
    if (props.api) {
      res = await props.api({...params,groupId: groupId.value, dataClassify: props.dataClassify})
    } else {
      res = await getElExcelData({...params,groupId: groupId.value, dataClassify: props.dataClassify})
    }
    
    loading.value = false
    let sheet = res.sheets[0]
    // 处理tableData
    sheet.secondExcelSheetList.forEach((sheetData: Record<'headers'|'dataList', any[]>, sheetIndex) => {
      let columns:BasicColumn[] = []
      let restArray:BasicColumn[] = []
      
      let data:any[] = sheetData.dataList.map(item => {
        const values = Object.values(item)
        let obj = {}
        values.forEach((value:any) => {
          if (!obj[value.field + 'sort' + value.sort])  obj[value.field + 'sort' + value.sort] = {
            ...value
          }
        })
        return obj
      })
      let fiexdIndex
      if (isArray(props.fiexdIndex)) {
        fiexdIndex = props.fiexdIndex[sheetIndex]
      } else {
        fiexdIndex = props.fiexdIndex
      }
      let colSpanHeaders = cloneDeep(sheetData.headers).slice(0, +fiexdIndex).filter(item => item.field).map(item => item.field+'sort')
      console.log(colSpanHeaders, 'colSpanHeaders')
      const filterHeaders = sheetData.headers.filter(item => item.field)
      let totalHeader:any[] = []
      filterHeaders.forEach(item => {
        totalHeader.push({...item, field: item.field+'sort0'})
        if (item.colSpan > 1 && !item.children) {
          for(let i = 1; i < item.colSpan;i++) {
            totalHeader.push({
              ...item,
              colSpan: 0,
              field: item.field + 'sort'+i
            })
          }
          
        }
      })
      console.log(filterHeaders, 'filterHeaders')
      totalHeader.forEach((item, index) => {
        let rest:BasicColumn = {
          title: item.name,
          colSpan: item.colSpan,
          edit: true,
          editable: false,
          ellipsis: false,
          fixed: colSpanHeaders.includes(item.field.substring(0,item.field.length - 1)) ? 'left' : false,  
          cellEdit: (value, column, index) => {
            return !!value.isWrite
          },
          format: (text) => {
            return text?.value
          },
          cellEditFileld: 'value',
          editValueMap: (value) => {
            return value.value
          },
          // customCell: (record, index, column) => {
          //   return {
          //     style: record[column?.dataIndex].isWrite ? 'border:1px solid #0067cc !important;' : ''
          //   }
          // },
          children: item.children?.map((child,index) => ({
            title: child.name,
            colSpan: child.colSpan,
            dataIndex: child.field + 'sort'+index,
            format: (text) => {
              return text?.value
            },
            customCell: (_, _index) => {
              let col = { }
              let colSpan = 1
              let rowSpan = 1
              if (colSpanHeaders.includes(item.field.substring(0,item.field.length - 1))) {
                child.field = child.field.indexOf('sort') > -1?child.field : child.field + 'sort'+index
                if (index == 0 || (_[item.children[index + 1]?.field] && _[item.children[index + 1]?.field].value == _[child.field].value && _[item.children[index - 1]?.field].value != _[child.field].value) ) {
                  colSpan = _[child.field]?.value ? Object.values(_).filter(val => val.value == _[child.field]?.value).length : 1
                } else if (index > 0 && _[child.field] && _[item.children[index - 1]?.field]?.value == _[child.field]?.value) {
                  colSpan = 0 
                } else {
                  colSpan = 1
                }
                while(data[_index][child.field].value !== _[child.field].value) {
                  _index = _index + (props.pagination?.pageSize || 0)
                }
                if (
                  _index > 0 &&
                  data[_index - 1][child.field]?.value &&
                  _[child.field].value === data[_index - 1][child.field].value
                ) {
                  rowSpan = 0 // 返回0表示在有跨度的行中不需要渲染，如果不为0，会被跨度合并时挤出到其他列显示
                } else {
                  let total = 1
                  if (_[child.field]?.value) {
                    data.some((currentValue, index) => {
                      if (index > _index) {
                        if (currentValue[child.field].value === _[child.field].value) {
                          total++
                          return false
                        } else {
                          return true
                        }
                      }
                    })
                  } else {
                    total = 1
                  }
                  rowSpan = total
                }
              }
              col = { rowSpan, colSpan }
              return col
            }
          }))
        }
        if (colSpanHeaders.includes(item.field.substring(0,item.field.length - 1))) {
          rest.customCell = (_, _index:any) => {
            let col = { }
            let colSpan = 1
            let rowSpan = 1
            if (index == 0 || (_[totalHeader[index + 1]?.field] && _[totalHeader[index + 1]?.field].value == _[item.field].value && _[totalHeader[index - 1]?.field].value != _[item.field].value) ) {
              colSpan = _[item.field].value ? Object.values(_).filter(val => val.value == _[item.field].value).length : 1
            } else if (index > 0 && _[item.field] && _[totalHeader[index - 1]?.field]?.value == _[item.field].value) {
              colSpan = 0 
            } else {
              colSpan = 1
            }

            while(data[_index][item.field].value !== _[item.field].value) {
              _index = _index + (props.pagination?.pageSize || 0)
            }
            if (
              _index > 0 &&
              data[_index - 1][item.field]?.value &&
              _[item.field].value === data[_index - 1][item.field].value
            ) {
              rowSpan = 0 // 返回0表示在有跨度的行中不需要渲染，如果不为0，会被跨度合并时挤出到其他列显示
            } else {
              let total = 1
              if (_[item.field]?.value) {
                data.some((currentValue, index) => {
                  
                  if (index > _index) {
                    if (currentValue[item.field].value === _[item.field].value) {
                      total++
                      return false
                    } else {
                      return true
                    }
                  }
                })
              } else {
                total = 1
              }
              rowSpan = total
            }
            col = { rowSpan, colSpan }
            return col
          }
        }
        // if (item.colSpan > 1 && !item.children) {
        //   rest.dataIndex = item.field
        //   restArray.push(rest)
        //   for(let i = 1; i < item.colSpan;i++) {
        //     restArray.push({
        //       ...rest,
        //       colSpan: 0,
        //       dataIndex: item.field + 'sort'+i,
        //       customCell: (_, index) => {
        //         let col = {}
        //         if (_[item.field + 'sort'+i].value === _[item.field].value) {
        //           col = { colSpan: 0 }
        //         }
        //         return col
        //       }
        //     })
        //   }
          
        // } else {
        //   rest.dataIndex = item.field
        //   restArray.push(rest)
        // }
        rest.dataIndex = item.field
        restArray.push(rest)
      })
      columns.push(...restArray)
      console.log(columns, 'columns')
      let notConcantForm = ['ecsQuotaBG_statement_form', 'gas_statement_form', 'ecsQuota_statement_form']
      let len = !notConcantForm.includes(props.groudIdDict) ? 1 : 2
      if (tableConfigs.value.length < len) {
         tableConfigs.value.push({
          tableData: data,
          columns: columns,
          title: sheetData.headers[0].name
        })
      } else {
        if (!tableConfigs.value[len]) tableConfigs.value[len] = []
        tableConfigs.value[len].push({
          tableData: data,
          columns: columns,
          title: sheetData.headers[0].name
        })
      }
     
    })
  }catch{
    loading.value = false
  }
}
let exportLoading = ref(false)
const handleExport = async () => {
  const params = await getFieldsValue()
  let api:any = null
  if (props.exportApi) {
    api = props.exportApi
  } else {
    api = exportElExcelData
  }
  const { data, headers } = await api({...params,groupId: groupId.value, dataClassify: props.dataClassify})
  let contentDisposition = decodeURIComponent(headers["content-disposition"])
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName)
  exportLoading.value = false
}
onMounted(async () => {
  const res = await getDictListByCode('electricity_statement')
  groupId.value = res.find(item => item.itemName === props.groudIdDict)?.itemCode || '1'
  //  const startDaysAgo = dayjs().subtract(30, 'days').format('YYYY-MM-DD')
  // console.log(startDaysAgo, dayjs().format('YYYY-MM-DD'), 'startDaysAgo')
  await setFieldsValue({
    'queryType': 'year',
  })
  nextTick(() => {
    handleSearch()
  }) 
})
</script>
<style lang="less" scoped>
  .common-search {
    padding: 12px 8px 0;
    border-radius: 2px;
    background-color: var(--component-background-color);
  
    :deep(.ant-form-item) {
      margin-bottom: 12px;
    }
  
    :deep(.ant-row>.ant-col:last-child) {
      flex: 1;
      max-width: none;
    }
  }
  .excel-form-model{
    :deep(.vben-page-wrapper-content) {
      display: flex;
      flex-direction: column;
    }
  }
  .table-box{
    flex: 1;
  }
  .content-box{
    height: calc(100% - 46px);
    overflow: auto;
  }
</style>